package devmento.gae.dao;


import javax.jdo.PersistenceManager;

import org.springframework.stereotype.Component;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import devmento.gae.PMF;
import devmento.gae.model.User;


@Component
public class UserDaoJdo {
	
	public void create(User user){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		try{
			Key key = KeyFactory.createKey(User.class.getSimpleName(), user.getId());
			user.setKey(key);
			pm.makePersistent(user);
		}finally{
			pm.close();
		}
	}
	
	public User find(String id){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		Key key = KeyFactory.createKey(User.class.getSimpleName(), id);
		
		User detached = null;
		
		try{
			User user = pm.getObjectById(User.class, key);
			detached = pm.detachCopy(user);
		}finally{
			pm.close();
		}
		
		return detached;
	}
	
	public void delete(String id){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		Key key = KeyFactory.createKey(User.class.getSimpleName(), id);
				
		try{
			User u = pm.getObjectById(User.class, key);
			pm.deletePersistent(u);
		}finally{
			pm.close();
		}
	}
	
	public void update(User user){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		Key key = KeyFactory.createKey(User.class.getSimpleName(), user.getId());
				
		try{
			User u = pm.getObjectById(User.class, key);
			u.setAge(user.getAge());
			u.setName(user.getName());
		}finally{
			pm.close();
		}
	}
	

}
